package com.hyg.common.utils;

import android.os.Build;

import androidx.annotation.RequiresApi;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;

/**
 * Author: huangyuguang
 * Date: 2022/5/5
 * Description: OkHttp框架Cookie管理类
 */
public class CookieJarManager implements CookieJar {

    private final String TAG = "CookieJarManager";

    private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();
    private final HashMap<String, String> cookieStr = new HashMap<>();

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
        if (null == url || null == cookies || cookies.size() <= 0) {
            return;
        }
        LogUtils.d("OkHttp","<-- cookies: " + cookies.toString());
        List<Cookie> newCookies = new ArrayList<>(cookies);
        List<Cookie> oldCookies = cookieStore.get(url.host());
        if(oldCookies != null){
            for (Cookie cookie : oldCookies) {
                boolean isSame = false;
                for(Cookie cookie1 : cookies){
                    if(cookie.name().equals(cookie1.name())){
                        isSame = true;
                        break;
                    }
                }
                if(!isSame){
                    newCookies.add(cookie);
                }
            }
        }
        cookieStore.put(url.host(), newCookies);

        StringBuffer cookieBuffer = new StringBuffer();
        for(Cookie cookie: newCookies){
            cookieBuffer.append(cookie).append(";");
        }
        cookieStr.put(url.host(),cookieBuffer.toString());
//        for (Cookie cookie : cookies) {
//            Log.d(TAG, "cookie Name:" + cookie.name());
//            Log.d(TAG, "cookie Path:" + cookie.path());
//        }
    }

    @Override
    public List<Cookie> loadForRequest(HttpUrl url) {
        if (null != url) {
            List<Cookie> cookies = cookieStore.get(url.host());
            if(cookies!=null && cookies.size()>0){
                LogUtils.d("OkHttp","--> cookies: " + cookies.toString());
            }
            return cookies != null ? cookies : new ArrayList<Cookie>();
        } else {
            return new ArrayList<Cookie>();
        }
    }

    public void clearCookie(){
        cookieStore.clear();
        cookieStr.clear();
    }

    public String getCookieStr(String host){
        return cookieStr.get(host);
    }
}